﻿var spListServerRelativeUrl = "";

function ShowSelectCamlFolderDialog(btnSelectCamlFolder) {
    ShowSelectCamlFolderDialog_Init();
    $('#selectCamlFolderDialog').modal();
}

function ShowSelectCamlFolderDialog_Init() {
    $('#jstreeSelectCamlFolder').parent().html('<div id="jstreeSelectCamlFolder"></div>');

    var spListOdataUrl = $("#spListOdataUrl").text();
    var spListParentWebUrl = spListOdataUrl + "?$select=ParentWebUrl";

    RestCallWithDeferred(spListParentWebUrl).then(
            function (data, object) {

                var parentWebUrl = data.d.ParentWebUrl;
                var spListFieldsOdataUrl = spListOdataUrl + "/RootFolder";

                RestCallWithDeferred(spListFieldsOdataUrl).then(
                    function (data, object) {
                        spListServerRelativeUrl = data.d.ServerRelativeUrl;
                        spListServerRelativeUrl = spListServerRelativeUrl.replace(parentWebUrl + '/', '')
                        var foldersArray = spListServerRelativeUrl.split('/');
                        var folderTitle = foldersArray[foldersArray.length - 1]
                        $('#jstreeSelectCamlFolder')
                        .on('changed.jstree', jstreeSelectCamlFolder_onChange)
                        .jstree({
                            'core': {
                                'data': [{ 'text': folderTitle, 'data': { spDataLoaded: false, folderUrl: spListServerRelativeUrl } }],
                                check_callback: true
                            },
                            plugins: ["dnd"]
                        });
                    },
                    function (XMLHttpRequest, textStatus, errorThrown) {
                        errorHandler(XMLHttpRequest, textStatus, errorThrown);
                    }
                );
            },
            function (XMLHttpRequest, textStatus, errorThrown) {
                errorHandler(XMLHttpRequest, textStatus, errorThrown);
            }
        );
}

function GetListParentWebUrl(spListOdataUrl) {
    
}

function RestCallWithDeferred(spListParentWebUrl) {
    var deferred = $.Deferred();
    
    $.ajax({
        url: spListParentWebUrl,
        type: "GET",
        headers: { "ACCEPT": "application/json;odata=verbose" },
        success: deferred.resolve,
        error: deferred.reject
    });

    return deferred.promise();
}

function jstreeSelectCamlFolder_onChange(e, data) {
    var selectedNodeId = data.selected[0];
    var selectedNode = data.instance.get_node(selectedNodeId);
    var selectedNodefolderUrl = selectedNode.data.folderUrl;
    var isSelected = selectedNode.state.selected;

    if (selectedNode.data.spDataLoaded === false) {
        jstreeSelectCamlFolder_Expand(selectedNodefolderUrl, selectedNodeId);
    }
}

function jstreeSelectCamlFolder_Expand(selectedNodefolderUrl, selectedNodeId) {
    var viewFields = "<ViewFields><FieldRef Name='FileLeafRef' /></ViewFields>";
    var siteUrl = $("#txtRootWebUrl").val();
    var listTitle = $("#spListTitle").text()
    var includeFields = "FileLeafRef";
    var objJStreeSelectCamlFolder = $('#jstreeSelectCamlFolder').jstree(true);

    GetSPListFolders(siteUrl, listTitle, includeFields, selectedNodefolderUrl).then(
            function (camlItems) {
                var listItemEnumerator = camlItems.getEnumerator();
                while (listItemEnumerator.moveNext()) {
                    var listItem = listItemEnumerator.get_current();
                    var fileLeafRef = listItem.get_item('FileLeafRef');
                    var folderUrl = selectedNodefolderUrl + '/' + fileLeafRef;
                    var newNode = { 'text': fileLeafRef, 'data': { spDataLoaded: false, folderUrl: folderUrl } };
                    var result = objJStreeSelectCamlFolder.create_node(selectedNodeId, newNode, "last", function (obj) { console.log('Node created' + fileLeafRef); });
                }
                objJStreeSelectCamlFolder.get_node(selectedNodeId).data.spDataLoaded = true;
                objJStreeSelectCamlFolder.open_node(selectedNodeId);
            },
            function (sender, args) {
                alert('An error occured while retrieving list items:' + args.get_message());
            }
        );
}

function GetSPListFolders(siteUrl, listTitle, includeFields, selectedNodefolderUrl) {
    var deferred = $.Deferred();
    var clientContext = new SP.ClientContext(siteUrl);
    var list = clientContext.get_web().get_lists().getByTitle(listTitle);

    var camlQuery = new SP.CamlQuery();
    camlQuery.set_folderServerRelativeUrl(selectedNodefolderUrl);
    camlQuery.set_viewXml("<View>" + 
                          "<ViewFields>" + 
                            "<FieldRef Name='FileLeafRef' />" + 
                          "</ViewFields>" + 
                          "<Query>" + 
                            "<Where>" + 
                              "<Eq>" + 
                                "<FieldRef Name='FSObjType' />" + 
                                "<Value Type='Lookup'>1</Value>" + 
                              "</Eq>" + 
                            "</Where>" + 
                          "</Query>" + 
                        "</View>");
    var items = list.getItems(camlQuery);
    
    clientContext.load(items, "Include(" + includeFields + ")");
    clientContext.executeQueryAsync(
        Function.createDelegate(this,
            function () { deferred.resolve(items); }),
        Function.createDelegate(this,
            function (sender, args) { deferred.reject(sender, args); }));

    return deferred.promise();
}

function btnSelectCamlFolderValue_OnClick(btnSelectCamlFolderValue) {
    var objJStreeSelectCamlFolder = $('#jstreeSelectCamlFolder').jstree();
    var selectedNodeId = objJStreeSelectCamlFolder.get_selected()[0];
    if (selectedNodeId) {
        var selectedNode = objJStreeSelectCamlFolder.get_node(selectedNodeId);

        $("#txtCamlQueryServerRelativeUrl").val(selectedNode.data.folderUrl);
        $('#selectCamlFolderDialog').modal('hide');
    }
    else {
        alert('Please select folder');
    }
}